# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from .MyIO import *
from .ConnFreeswitch import *
from .MySqlite import *
import xadmin

config_file_patch = "/usr/local/freeswitch/conf/"
getcwd="/var/www/MyIPPbx"
#UPLOAD_PATH_FILE = "/usr/local/freeswitch/sounds/zh/cn/callie/misc/"
selectsql = "select id,name,number from pbx_localextension  ORDER BY sort"
class LocalExtensionAdmin(object):
    list_display = ['name', 'number', 'sort']
    list_per_page = 10
    add_form_template = 'myform.html'
    change_form_template = 'myform.html'
    search_fields = ['name', 'number']
    xadmin.views.edit.UpdateAdminView.exclude = ['name']

    def save_models(self):
        obj = self.new_obj
        urllist = str(self.request.get_full_path()).split('/')
        if len(urllist) == 5:
            sql="INSERT INTO pbx_localextension(name,number,sort)VALUES('"+obj.name+"','"+obj.number.replace("d","\d")+"','"+str(obj.sort)+"')"
        else:
            sql="update pbx_localextension set number='"+obj.number.replace("d","\d")+"',sort='"+str(obj.sort)+"' where id="+urllist[3]
        ComSql(sql)
        writeLocal(selectsql)
        r = ReloadXml()
        if r == -1:
            self.message_user(u'告警,IPPBX加载失败，请重启IPPBX或者手动加载!', 'warning')

    def delete_models(self, obj):
        #deleteFile(obj, config_file_patch + "dialplan/default/", "_out.xml")
        obj.delete()
        writeLocal(selectsql)
        r = Reloadacl()
        if r == -1:
            self.message_user(u'告警,IPPBX加载失败，请重启IPPBX或者手动加载!', 'warning')

def writeLocal(strsql):
    info = ReadFile(os.path.join(getcwd + "/pbx/tpl", 'Local_Extension.xml'))
    strcontent = ""
    aclList = ReadSql(strsql)
    for i in aclList:
        strcontent += info.replace('{name}', i[1]).replace('{number}', i[2])+"\r\n"
    strDefault = ReadFile(config_file_patch+"dialplan/default.xml")
    intBegin = strDefault.find("<!-- Local Extension begin -->")
    intend = strDefault.find("<!-- Local Extension end -->")
    strBefin = strDefault[:intBegin]+"<!-- Local Extension begin -->"
    strEnd = strDefault[intend:]
    strcontent = strBefin+"\r\n" + strcontent + strEnd
    WriteFile(config_file_patch + "dialplan/default.xml", strcontent)
    #print strBefin+"<!-- Local Extension begin -->"
    #print "-----------------------------------------"
    #print strEnd